//
//  JBSBusMainViewController.m
//  changwonbus
//
//  Created by park juram on 12. 11. 20..
//  Copyright (c) 2012년 park juram. All rights reserved.
//

#import "JBSBusMainViewController.h"
#import "JBSBusMainTableViewCell.h"
#import "HttpRequest.h"
#import "HTMLParser.h"
#import "HTMLNode.h"
#import "JBSBusDetailViewController.h"

@interface JBSBusMainViewController ()

@end

@implementation JBSBusMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    // make cancle button
    [_searchBar setShowsCancelButton:YES animated:YES];
    return true;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    // make cancle button
    [_searchBar setShowsCancelButton:NO animated:YES];
    return true;
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ( _dataArray == nil ) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    [_dataArray removeAllObjects];
    
    NSString *url = @"http://bus.changwon.go.kr/busInfo/busInfoDetail.jsp";
    
    // HTTP Request 인스턴스 생성
    HttpRequest *httpRequest = [[HttpRequest alloc] init];
    
    // POST로 전송할 데이터 설정
    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:
								@"0", @"ra_type",
								[_searchBar text], @"search_title",
								nil];
	//NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";
    
    // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
    
    // 페이지 호출
    [httpRequest requestUrl:url bodyObject:bodyObject];
    
    
}

-(void)didReceiveFinished:(NSString *)receiveString
{
    HTMLParser *parser = [[HTMLParser alloc]
                          initWithString:receiveString error:nil];
    
    HTMLNode *bodyNode = [parser body];
    NSArray *searchResult = [[[bodyNode findChildOfClass:@"search_result"] findChildOfClass:@"scroll"] findChildTags:@"tr"];
    
    for ( int i=0; i<[searchResult count]; i++ ) {
        HTMLNode *numberNode = [[searchResult objectAtIndex:i] findChildWithAttribute:@"width" matchingName:@"35" allowPartial:YES];
        HTMLNode *pathNode = [[searchResult objectAtIndex:i] findChildWithAttribute:@"width" matchingName:@"150" allowPartial:YES];
        NSString *busNumberId = [[[searchResult objectAtIndex:i] findChildTag:@"a"] getAttributeNamed:@"onclick"];
        
        NSRange startPos = [busNumberId rangeOfString:@"'"];
        NSRange endPos = [busNumberId rangeOfString:@"'," options:NSBackwardsSearch];
        startPos.location += 1;
        
        startPos.length = endPos.location - startPos.location;
        busNumberId = [busNumberId substringWithRange:startPos];
        NSLog( @"%@", busNumberId );
        
        if ( numberNode != nil ) {
            NSDictionary *data = [[NSDictionary alloc]initWithObjectsAndKeys:[numberNode contents],@"number", [pathNode contents], @"path", busNumberId, @"numberId", nil];
            [_dataArray addObject:data];
//            NSLog(@"%@", [numberNode contents] );
        }
    };
    [_busTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark -
-(void)viewWillAppear:(BOOL)animated
{
    // Register the observer for the keyboardWilShow event
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)keyboardWillShow:(NSNotification *)notification
{
    // create done button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"doneup.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"donedown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(doneButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

    // locate keyboard view
    UIWindow *tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView *keyboard;
    for (int i = 0; i < [tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if ([[keyboard description] hasPrefix:@"<UIPeripheralHostView"] == YES) {
            [keyboard addSubview:doneButton];
        }
    }
}
-(BOOL)doneButtonClicked:(UITextField *)theTextField
{
    [_searchBar resignFirstResponder];
    [self searchBarSearchButtonClicked:_searchBar];
    return YES;
}

#pragma mark -


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"BusMainTableCell";
    static BOOL nibsRegistered = NO;
    if ( !nibsRegistered ) {
        UINib *nib = [UINib nibWithNibName:@"BusMainTableCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        nibsRegistered = YES;
    }
    
    JBSBusMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    NSInteger row = [indexPath row];
    NSDictionary *rowData = [_dataArray objectAtIndex:row];
    
    NSString *numberStr = [[NSString alloc]initWithFormat:@"%@번", [rowData objectForKey:@"number"] ];
    [cell.busNumber setText:numberStr];
    [cell.busPath setText:[rowData objectForKey:@"path"]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSUInteger *row = [indexPath row];
    [_searchBar resignFirstResponder];
    [self performSegueWithIdentifier: @"busDetail" sender: self];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"busDetail"]) {
        NSIndexPath *indexPath = [_busTableView indexPathForSelectedRow];
        NSInteger row = [indexPath row];
        NSDictionary *rowData = [_dataArray objectAtIndex:row];
        
        JBSBusDetailViewController *destViewController = segue.destinationViewController;
        destViewController.busNumber = [[NSString alloc]initWithFormat:@"%@번", [rowData objectForKey:@"number"]];
        destViewController.busPath = [[NSString alloc]initWithFormat:@"%@", [rowData objectForKey:@"path"]];
        destViewController.busNumberId = [rowData objectForKey:@"numberId"];

    }
}

@end
